<template>
  <px-scrollbar v-if="!isMain && isView" class="view-equip-detail">
    <div class="view-task-detail">
      <div class="view-task-title">
        <px-button type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
        <div class="text">{{ taskDetailData.taskName }}</div>
        <div class="status">
          <div class="circle" :style="{ backgroundColor: `${tagBgColorList[taskDetailData.taskStatus]}` }" />
          <p :style="{ color: `${tagBgColorList[taskDetailData.taskStatus]}` }">
            {{ taskDetailData.taskStatusDesc }}{{ taskDetailData.timeOut ? "(超期)" : "" }}
          </p>
        </div>
      </div>
      <div>
        <px-button
          v-if="taskDetailData.taskStatus === 1 && taskDetailData.isInGroup"
          v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_COLLECT'"
          type="primary"
          @click="handleCollect"
        >
          领取任务
        </px-button>
        <px-button
          v-if="taskDetailData.taskStatus === 2 && (taskDetailData.executorId === userId || planDetailData.createBy === userId)"
          v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_FORWARD'"
          type="primary"
          plain
          @click="isForwardShow = true"
        >
          转派任务
        </px-button>
        <px-button
          v-if="
            (taskDetailData.executorId === userId || planDetailData.createBy === userId) &&
            [2, 3].includes(taskDetailData.taskStatus) &&
            taskDetailData.isTransfer !== 1
          "
          v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_MAINTAIN'"
          type="primary"
          plain
          @click="handleToMaintainTask"
        >
          转维修工单
        </px-button>
        <px-button
          v-if="taskDetailData.executorId === userId && taskDetailData.taskStatus === 2"
          v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_EXECUTE'"
          type="primary"
          @click="handleExecute"
        >
          执行任务
        </px-button>
      </div>
    </div>
    <CustomTabs :tabList="tabList" :activeName="activeName" @tabSelect="handelTabSelected" />
    <TaskDetail v-if="activeName === 'first'" :taskDetailData="taskDetailData" :moduleName="moduleName" />
    <PlanDetail v-if="activeName === 'second'" :planDetailData="planDetailData" />
    <ForwardDialog :visible="isForwardShow" :rowData="taskDetailData" @closeDialog="isForwardShow = false" @queryTable="ForwardBack" />
  </px-scrollbar>
</template>
<script lang="ts" setup>
import { collectExceptionTask, detailCollectExceptionTask, detailExceptionList, detailExceptionTask, getTaskModuleName } from "@/api/equip/exception";
import CustomTabs from "@/components/Tabs/index.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, toRefs, watchEffect } from "vue";
import { useRouter } from "vue-router";
import PlanDetail from "../../plan/components/PlanDetail.vue";
import ForwardDialog from "./ForwardDialog.vue";
import TaskDetail from "./TaskDetail.vue";

const router = useRouter();

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable", "handleExecute"]);

// 父级传过来的值
const props = defineProps(["isMain", "isView", "taskNo", "taskStatus", "userId"]);

// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);

const state = reactive<any>({
  taskDetailData: {},
  planDetailData: {},
  activeName: "first",
  tabList: [
    {
      name: "first",
      label: "点检任务"
    },
    {
      name: "second",
      label: "点检计划"
    }
  ],
  isForwardShow: false,
  moduleName: ""
});
const { activeName, taskDetailData, planDetailData, tabList, isForwardShow, moduleName } = toRefs(state);

const tagBgColorList = {
  0: "#909399", // 取消
  1: "#F59E0B", // 待接单
  2: "#3B82F6", // 执行中
  3: "#10B981" // 已完成
};

// 获取getModuleName
const getModuleNameValue = async () => {
  const data = await getTaskModuleName();
  moduleName.value = data;
};

const ForwardBack = () => {
  emits("queryTable");
  backMainPage();
};

watchEffect(async () => {
  if (props.isView && !props.isMain) {
    getModuleNameValue();
    // 获取点检任务的详情
    // 待接单或者已取消的状态调用领取点检任务详情
    if (props.taskStatus === 1 || props.taskStatus === 0) {
      const taskRes = await detailCollectExceptionTask(props.taskNo);
      const { images } = taskRes;
      if (images?.length > 0) {
        images?.forEach(item => {
          item.url = item.fileUrl;
        });
        taskRes.imageIds = taskRes.images;
      } else {
        taskRes.imageIds = [];
      }
      taskDetailData.value = { ...taskRes, imageIds: images };
    } else {
      // 其他状态调用执行任务详情
      const taskRes = await detailExceptionTask(props.taskNo);
      const { images } = taskRes;
      if (images?.length > 0) {
        images?.forEach(item => {
          item.url = item.fileUrl;
        });
        taskRes.imageIds = taskRes.images;
      } else {
        taskRes.imageIds = [];
      }
      taskDetailData.value = { ...taskRes, imageIds: images };
    }
  }
});

const getDetail = async planNo => {
  const res = await detailExceptionList(planNo);
  const { images } = res;
  if (images?.length > 0) {
    images?.forEach(item => {
      item.url = item.fileUrl;
    });
    res.imageIds = res.images;
  } else {
    res.imageIds = [];
  }
  planDetailData.value = { ...res, imageIds: images };
};

const handelTabSelected = selectName => {
  activeName.value = selectName;
  if (selectName === "second") {
    getDetail(taskDetailData.value.planNo);
  }
};

// 执行
const handleExecute = () => {
  emits("handleExecute", taskDetailData.value, true);
};

// 领取
const handleCollect = () => {
  PxMessageBox.confirm(`确认领取该任务吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    draggable: true,
    type: "warning"
  })
    .then(async () => {
      await collectExceptionTask(props.taskNo);
      PxMessage.success("领取成功");
      handleExecute();
    })
    .catch(() => {});
};

const handleToMaintainTask = () => {
  router.push(`/all/equip/maintain/task?exception=${props.taskNo}`);
};

const backMainPage = () => {
  activeName.value = "first";
  taskDetailData.value = {};
  emits("backMainPage");
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/view-detail.scss");

.view-equip-detail {
  padding: 20px;
}

.view-task-detail {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;

  .view-task-title {
    display: flex;
    flex-direction: row;
    align-items: center;

    .text {
      margin-right: 8px;
      margin-left: 16px;
      font-size: 20px;
      font-weight: 600;
      line-height: 1;
      color: rgb(0 0 0 / 90%);
    }

    .status {
      display: flex;
      flex-direction: row;
      align-items: center;
      line-height: 1;

      .circle {
        width: 8px;
        height: 8px;
        margin-right: 5px;
        border-radius: 50%;
      }
    }
  }
}
</style>
